//
//  Resource_TabViewController.m
//  CMVRFForIOS
//
//  Created by HailongHan on 15/3/27.
//  Copyright (c) 2015年 hvacapp. All rights reserved.
//

#import "Resource_TabViewController.h"
#import "UITapView.h"
#import "NoticeListDataResponse.h"
#import "NoticeTableViewCell.h"
#import "PostData.h"
#import "ResourceURLViewController.h"
#import "NoticeViewController.h"
#import "MJRefresh.h"

#define NOTICE_Cell_Indentifier @"NoticeCell"
@interface Resource_TabViewController () {
    NSUInteger beginIndex;
    NSUInteger endIndex;
}

@property (strong, nonatomic) UISegmentedControl *segmentControl;

@property (nonatomic,strong) UIView *actionView;

@property (nonatomic,strong) UITableView *tableView;

@property (nonatomic,strong) NSMutableArray *dataSource;



@end

@implementation Resource_TabViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self initData];
    [self setupViews];
    [self loadData];
}

/**
 *  初始化数据
 */
- (void)initData {
    self.dataSource = [NSMutableArray new];
    beginIndex = 0;
    endIndex = LIST_PAGE_ITEM_COUNTS - 1;
}


#pragma mark - 初始化视图
- (void)setupViews{
    self.title = @"资源";
    
    self.segmentControl = [[UISegmentedControl alloc] initWithItems:@[@"体验", @"公告"]];
    self.navigationItem.titleView = self.segmentControl;
    
    [self.segmentControl addTarget:self action:@selector(switchView) forControlEvents:UIControlEventValueChanged];
    [self.segmentControl setWidth:80.0 forSegmentAtIndex:1];//设置指定索引选项的宽度
    [self.segmentControl setWidth:80.0 forSegmentAtIndex:0];//设置指定索引选项的宽度
    
    //初始显示信息
    [self.segmentControl setSelectedSegmentIndex:0];
    
    
    self.actionView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreen_Width, 0)];
    [self.view addSubview:self.actionView];
    [self setupActionView];
    
    self.tableView = [[UITableView alloc] initWithFrame:[UIView frameWithOutNavTab] style:UITableViewStylePlain];
    self.tableView.backgroundColor = [UIColor whiteColor];
    [self.tableView registerClass:[NoticeTableViewCell class] forCellReuseIdentifier:NOTICE_Cell_Indentifier];
    [self.tableView setTableFooterView:[[UIView alloc] initWithFrame:CGRectZero]];
    //去掉分割线
    //self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.hidden = YES;
    
    //下拉刷新
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        // 进入刷新状态后会自动调用这个block
        if (_segmentControl.selectedSegmentIndex == 0) {
            return;
        }
        [self refreshData];
    }];
    //上拉加载
    self.tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        if (_segmentControl.selectedSegmentIndex == 0) {
            return;
        }
        [self loadMoreData];
    }];
    
    [self.view addSubview:self.tableView];

}


- (void)setupActionView {
    //产品介绍入口
    UITapView *view1 = [[UITapView alloc]initWithFrame:CGRectMake(kScreen_Width/2 + 2, 0, kScreen_Width/2 - 2, kScreen_Width/4)];
    [view1 setBgColor:CM_ACTION_CELL_COLOR andHighLightBgColor:CM_ACTION_CELL_HIGH_LIGHT_COLOR];
    [view1 addTargetsBlock:^(id obj) {
        ResourceURLViewController *view = [ResourceURLViewController new];
        view.resourceType = 0;
        [self.navigationController pushViewController:view animated:YES];
    }];
    [self.actionView addSubview:view1];
    
    UIImageView *image1 = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"series_introduce"]];
    image1.centerX = view1.width/2;
    image1.centerY = view1.height/2 - 10;
    [view1 addSubview:image1];
    
    UILabel *title1 = [UILabel labelSingleLineFontSize:kActionBarFontSize content:@"产品介绍"];
    title1.textColor = CM_BLUE_COLOR;
    title1.centerX = view1.width/2;
    title1.y = CGRectGetMaxY(image1.frame) + 10;
    [view1 addSubview:title1];
    
    //厂家介绍入口
    UITapView *view2 = [[UITapView alloc]initWithFrame:CGRectMake(0, 0, kScreen_Width/2 - 2, kScreen_Width/4)];
    [view2 setBgColor:CM_ACTION_CELL_COLOR andHighLightBgColor:CM_ACTION_CELL_HIGH_LIGHT_COLOR];
    [view2 addTargetsBlock:^(id obj) {
        ResourceURLViewController *view = [ResourceURLViewController new];
        view.resourceType = 1;
        [self.navigationController pushViewController:view animated:YES];
    }];
    [self.actionView addSubview:view2];
    
    UIImageView *image2 = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"companny_introduce"]];
    image2.centerX = view2.width/2;
    image2.centerY = view2.height/2 - 10;
    [view2 addSubview:image2];
    
    UILabel *title2 = [UILabel labelSingleLineFontSize:kActionBarFontSize content:@"厂家介绍"];
    title2.textColor = CM_BLUE_COLOR;
    title2.centerX = view2.width/2;
    title2.y = CGRectGetMaxY(image2.frame) + 10;
    [view2 addSubview:title2];
    
    //样板工程入口
    UITapView *view3 = [[UITapView alloc]initWithFrame:CGRectMake(0, kScreen_Width/4 + 4, kScreen_Width/2 - 2, kScreen_Width/4)];
    [view3 setBgColor:CM_ACTION_CELL_COLOR andHighLightBgColor:CM_ACTION_CELL_HIGH_LIGHT_COLOR];
    [view3 addTargetsBlock:^(id obj) {
        ResourceURLViewController *view = [ResourceURLViewController new];
        view.resourceType = 2;
        [self.navigationController pushViewController:view animated:YES];
    }];
    [self.actionView addSubview:view3];
    
    UIImageView *image3 = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"sample_project"]];
    image3.centerX = view3.width/2;
    image3.centerY = view3.height/2 - 10;
    [view3 addSubview:image3];
    
    UILabel *title3 = [UILabel labelSingleLineFontSize:kActionBarFontSize content:@"样板工程"];
    title3.textColor = CM_BLUE_COLOR;
    title3.centerX = view3.width/2;
    title3.y = CGRectGetMaxY(image3.frame) + 10;
    [view3 addSubview:title3];
    
    //施工动画入口
    UITapView *view4 = [[UITapView alloc]initWithFrame:CGRectMake(kScreen_Width/2 + 2, kScreen_Width/4 + 4, kScreen_Width/2 - 2, kScreen_Width/4)];
    [view4 setBgColor:CM_ACTION_CELL_COLOR andHighLightBgColor:CM_ACTION_CELL_HIGH_LIGHT_COLOR];
    [view4 addTargetsBlock:^(id obj) {
        ResourceURLViewController *view = [ResourceURLViewController new];
        view.resourceType = 3;
        [self.navigationController pushViewController:view animated:YES];
    }];
    [self.actionView addSubview:view4];
    
    UIImageView *image4 = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"demo_video"]];
    image4.centerX = view4.width/2;
    image4.centerY = view4.height/2 - 10;
    [view4 addSubview:image4];
    
    UILabel *title4 = [UILabel labelSingleLineFontSize:kActionBarFontSize content:@"实景体验"];
    title4.textColor = CM_BLUE_COLOR;
    title4.centerX = view4.width/2;
    title4.y = CGRectGetMaxY(image4.frame) + 10;
    [view4 addSubview:title4];
    
    self.actionView.height = CGRectGetMaxY(view4.frame);
   
    
}

#pragma mark - 切换事件
-(void)switchView
{
    if (_segmentControl.selectedSegmentIndex == 0) {
        self.actionView.hidden = NO;
        self.tableView.hidden = YES;
    } else if (_segmentControl.selectedSegmentIndex == 1) {
        self.actionView.hidden = YES;
        self.tableView.hidden = NO;
    }
}

#pragma mark - 加载数据
/**
 *  加载视图所有的数据
 */
- (void)loadData {
    [self loadAllNoticesBegin:beginIndex andEnd:endIndex];
}

- (void)refreshData {
    // 马上进入刷新状态
    [self.tableView.mj_header beginRefreshing];
    
    beginIndex = 0;
    endIndex = LIST_PAGE_ITEM_COUNTS - 1;
    [self loadAllNoticesBegin:beginIndex andEnd:endIndex];
    
}

- (void)loadMoreData {
    //下级公司发布的意见
    if (self.dataSource.count == 0) {
        return;
    }
    // 马上进入刷新状态
    [self.tableView.mj_footer beginRefreshing];
    beginIndex = self.dataSource.count;
    endIndex = beginIndex + LIST_PAGE_ITEM_COUNTS - 1;
    [self loadAllNoticesBegin:beginIndex andEnd:endIndex];
}

- (void)loadAllNoticesBegin:(NSInteger)si andEnd:(NSInteger)ei {
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    [param setValue:[NSNumber numberWithInteger:si] forKey:@"si"];
    [param setValue:[NSNumber numberWithInteger:ei] forKey:@"ei"];
    [param setValue:[NSNumber numberWithInt:0] forKey:@"os"]; //1: 仅返回自己发布的公告 0: 返回自己和上级公司发布的公告
    
    [HttpClient getWithUrl:HTTP_GET_ALL_NOTICES token:[[AccountManager manager]token] paramDic:param resultClass:[PostData class] success:^(PostData *obj) {
            if (si == 0) {
                //下拉刷新
                [self.tableView.mj_header endRefreshing];
                [self.dataSource removeAllObjects];
            }
            else {
                //上拉加载更多
                [self.tableView.mj_footer endRefreshing];
            }
        if (obj.getPostResult != nil && obj.getPostResult.count > 0) {
            [self.dataSource addObjectsFromArray:obj.getPostResult];
        }
        [self.tableView reloadData];
    } failure:^(NSError *error) {
        if (si == 0) {
            //下拉刷新
            [self.tableView.mj_header endRefreshing];
            [self.dataSource removeAllObjects];
        }
        else {
            //上拉加载更多
            [self.tableView.mj_footer endRefreshing];
        }
        [self.tableView reloadData];
        CMLog(@"获取公告失败：%@", error);
    }];
}

- (void)readOneNotice:(NSString*)noticeId {
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    [param setValue:noticeId forKey:@"id"];
    
    [HttpClient getWithUrl:HTTP_GET_VIEW_NOTICE token:[[AccountManager manager]token] paramDic:param resultClass:[PostData class] success:^(PostData *obj) {
        //通知重新获取未读公告条数
        [[NSNotificationCenter defaultCenter] postNotificationName:@"refreshNoticeCount" object:nil];
    } failure:^(NSError *error) {
        CMLog(@"获取公告失败：%@", error);
    }];
    
}

#pragma mark - tableView显示设置数据
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataSource.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    NoticeTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:NOTICE_Cell_Indentifier];
    if (cell == nil) {
        cell = [[NoticeTableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:NOTICE_Cell_Indentifier];
    }
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    
    PostData *item = [self.dataSource objectAtIndex:indexPath.row];
    [cell setTitle:item.title andDetail:item.content andFrom:item.from andDate:[DateTools getChYearMonthDay:item.time]];
    [cell setNewNoticeFlag:item.viewed == 1 ? NO : YES];
    
    return cell;
}


-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    PostData *item = [self.dataSource objectAtIndex:indexPath.row];
    if (item.viewed == 0) {
        item.viewed = 1;
        [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
        [self readOneNotice:item.guidId];
    }
    NoticeViewController *view = [NoticeViewController new];
    view.viewType = KKView_Notice;
    view.titleStr = item.title;
    NSString *formatTime = [DateTools getChYearMonthDay:item.time];
    view.fromAndDateStr = [NSString stringWithFormat:@"%@  %@", item.from, formatTime];
    view.guidId = item.guidId;
    view.contentStr = item.content;
    [self.navigationController pushViewController:view animated:YES];
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    NoticeTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:NOTICE_Cell_Indentifier];
    if (cell == nil) {
        cell = [[NoticeTableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:NOTICE_Cell_Indentifier];
    }
    return [cell getHeight];
}



@end
